//
//  API.swift
//  DaRings
//
//  Created by 尹琼 on 2022/11/25.
//

import UIKit
import Moya

public enum API {
    
    /// OTA
    case OTA(target: OTATargetType)
    
    /// 下载
    case download(target: DownloadTargetType)
    
    /// 绑定配置
    case bandConfig(target: BandConfigTargeType)
    
}

public extension API {
    
     typealias sucessHandle = (_ response: Response) ->Void
     typealias failureHandle = (_ error: Error?) ->Void
    
     func response(progress: ProgressBlock? = nil, sucess: sucessHandle?, failure: failureHandle? ) {
        
        switch self {
        case .OTA(let target):
            
            let provider = MoyaProvider<OTATargetType>()
            
            provider.request(target) { result in
                
                self.parse(result, sucess: sucess, failure: failure)
            }
            
        case .download(let target):
            
            let provider = MoyaProvider<DownloadTargetType>()
            provider.request(target, progress: progress) { result in
                self.parse(result, sucess: sucess, failure: failure)
            }
            
        case .bandConfig(let target):
            let provider = MoyaProvider<BandConfigTargeType>()
            provider.request(target) { result in
                
                self.parse(result, sucess: sucess, failure: failure)
            }
        }
    }
    
}

extension API {
    
    fileprivate func parse(_ result: Result<Response, MoyaError>, sucess: sucessHandle?, failure: failureHandle?) {
        
        switch result {
            
        case .success(let res):
            if res.statusCode == 200 {
                sucess?(res)
            } else {
                failure?(nil)
            }
            
            return
            
        case .failure(let er):
            failure?(er)
            return
            
        }
    }
    
}
